/**
 * created by zt on 2018/04/20
 */
import React from "react";
import { InputNumber, Form, Button, Input, Icon, Radio, Alert } from "antd";
import { connect } from "react-redux";
import ConfigurationCenterModel from "containers/setting/configuration-center/configuration-center.model";
import ConfigurationCenterService from "containers/setting/configuration-center/configuration-center.service";
import Chooser from "components/chooser";
import config from "config";
import { deepCopy, messages } from "share/common";

const FormItem = Form.Item;

class EditRule extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentRule: deepCopy(ConfigurationCenterModel.configurationRule),
      configFactors: [],
      saving: false, // 保存
      formItemLayout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 14 },
      },
      resultDescription: "", // 校验规则描述
      configItem: {},
      currentRuleItem: null,
    };
  }

  /**
   * @description 改变props时触发
   *
   * */
  componentWillReceiveProps(nextProps) {
    if (nextProps.showRuleDetail === this.props.showRuleDetail) return;
    if (!nextProps.showRuleDetail) {
      this.props.form.resetFields();
      return !1;
    }
    const options = {
      saving: false,
      currentRule: nextProps.currentRule,
      resultDescription: nextProps.currentRule.configRule.valueDesc,
    };
    this.state.configFactors < 1 &&
      (options.configFactors = nextProps.configFactors);
    !this.state.configItem.id && (options.configItem = nextProps.configItem);
    this.setState(options, () => this.props.form.resetFields());
    // setTimeout(() => this.props.form.resetFields(), 10);
  }

  /**
   * @description 将configItem 转化成 configFactor 格式
   *
   * */
  configItemHandle = (configItem) => {
    return {
      factorName: messages("setting.key271" /*校验结果*/),
      factorType: configItem.resultType,
      factorCode: configItem.itemCode,
      isEnabled: true,
      required: "Y",
      hide: "N",
      url: `${config.baseUrl}/config/api/config/item/${configItem.id}/resultDataList`,
    };
  };

  /**
   * @description 设置搜索区搜索对象
   * @param configFactor ConfigFactor
   * */
  searchFormHandle = (configFactor) => {
    // 搜索区内容
    return [
      {
        type: "input",
        id: "param",
        label: `${configFactor.factorName || configFactor.fieldLabel}${messages(
          "setting.key197" /*名称*/
        )}`,
      },
    ];
  };

  /**
   * @description 表头处理
   * @param configFactor ConfigFactor
   * */
  columnsHandle = (configFactor) => {
    return [
      {
        title: `${configFactor.factorName || configFactor.fieldLabel}${messages(
          "setting.key197" /*名称*/
        )}`,
        dataIndex: "name",
        width: "30%",
        key: "name",
      },
      {
        title: `${configFactor.factorName || configFactor.fieldLabel}${messages(
          "setting.key278" /*描述*/
        )}`,
        dataIndex: "description",
        width: "60%",
        key: "description",
      },
    ];
  };

  /**
   * @description 获取默认值
   * @param factorCode String
   * */
  getInitialValue = (factorCode) => {
    const { currentRule, configItem } = this.state;
    let result = {};
    if (configItem.resultType === "DATALIST" && currentRule.configRule.value) {
      JSON.parse(currentRule.configRule.value).map((item) => {
        item.valueCode === factorCode && (result = item);
      });
    }
    return factorCode === "priority"
      ? currentRule.configRule.priority
      : currentRule.configRuleFactors
      ? {}
      : currentRule.configRuleFactorMap[factorCode]
      ? currentRule.configRuleFactorMap[factorCode]
      : result || {};
  };

  /**
   * @description 获取form表单单项选择内容
   * @param configFactor ConfigFactor
   *
   * */
  getFormItem = (configFactor) => {
    if (configFactor.hide === "Y") {
      return "";
    }
    const { getFieldDecorator } = this.props.form;
    const { formItemLayout } = this.state;
    const options = this.getOption(configFactor);
    const labelName = configFactor.factorName || configFactor.fieldLabel;
    const id = configFactor.factorCode || configFactor.valueCode;
    return (
      <FormItem label={`${labelName}:`} {...formItemLayout} key={labelName}>
        {getFieldDecorator(id, options)(this.getHtmlInput(configFactor))}
      </FormItem>
    );
  };

  getMapItem = () => {
    const { configItem, resultDescription, formItemLayout } = this.state;
    switch (configItem.resultType) {
      case "LIST":
        return (
          <FormItem
            className="validate-result-wrap"
            label={messages("setting.key271" /*校验结果*/)}
            {...formItemLayout}
          >
            <p>{messages("setting.key279" /*当符合规则，则*/)}</p>
            {this.getConfigItemHtml(configItem)}
            <p>{resultDescription}</p>
          </FormItem>
        );
      default:
        const mapItem = JSON.parse(configItem.dataConfig);
        return (
          <div className="validate-result-wrap">
            <p
              style={{
                color: "#333333",
                fontSize: "14px",
                lineHeight: "32px",
                width: "230px",
                textAlign: "right",
              }}
            >
              {messages("setting.key280" /*请设置返回结果*/)}：
            </p>
            {mapItem.map((item) => {
              if (
                item.fieldType === "LIST" ||
                item.fieldType === "MULTY_SEL_LIST"
              ) {
                item.url = `${config.baseUrl}/config/api/config/dataList?listCode=${item.dataConfig.listCode}&listType=${item.dataConfig.listType}`;
              }
              return this.getFormItem(item);
            })}
            <p
              style={{
                color: "#333333",
                fontSize: "14px",
                lineHeight: "32px",
                marginLeft: "50px",
              }}
            >
              {resultDescription}
            </p>
          </div>
        );
    }
  };

  /**
   *@description 判断是否为null值
   * @param value string | null | undefined
   * */
  isNull = (value) => {
    return ~["null", "undefined"].indexOf(`${value}`.toLowerCase());
  };

  /**
   * @description 获取验证对象
   *
   * */
  getOption = (configFactor) => {
    const requiredText = messages("common.name.is.required", {
      name: configFactor.factorName || configFactor.fieldLabel,
    });
    let initial = "";
    configFactor.factorCode
      ? (initial = this.getInitialValue(configFactor.factorCode)
          .factorValueDesc)
      : (initial = this.getInitialValue(configFactor.valueCode).valueDesc);
    const options = {
      rules: [
        {
          required: configFactor.required === "Y",
          message: requiredText,
        },
      ],
      initialValue: initial,
      key: configFactor.factorCode || configFactor.valueCode,
    };
    if (configFactor.factorType === "CHECKBOX") {
      const value = options.initialValue;
      options.initialValue = this.isNull(value) ? "NULL" : value.toUpperCase();
    }
    // LIST 初始化值需要额外处理
    if (
      configFactor.factorType === "LIST" ||
      configFactor.fieldType === "LIST"
    ) {
      const value = [];
      const initialValue = this.getInitialValue(
        configFactor.factorCode || configFactor.valueCode
      );
      if (initialValue && (initialValue.factorValue || initialValue.value)) {
        const valueItem = {
          id: initialValue.factorValue || initialValue.value,
          name: initialValue.factorValueDesc || initialValue.valueDesc,
        };
        value.push(valueItem);
      }
      options.initialValue = value;
    }
    if (
      configFactor.factorType === "MULTY_SEL_LIST" ||
      configFactor.fieldType === "MULTY_SEL_LIST"
    ) {
      const value = [];
      const initialValue = this.getInitialValue(
        configFactor.factorCode || configFactor.valueCode
      );
      if (initialValue && (initialValue.factorValue || initialValue.value)) {
        const ids = (initialValue.factorValue || initialValue.value).split(",");
        const names = (
          initialValue.factorValueDesc || initialValue.valueDesc
        ).split(",");
        ids.map((id, index) => {
          value.push({ id, name: names[index] });
        });
      }
      options.initialValue = value;
    }
    return options;
  };

  /**
   * @description 获取对应的标签
   * @param configFactor ConfigFactor { factorType: }
   *
   * */
  getHtmlInput = (configFactor) => {
    let result = "";
    switch (configFactor.factorType || configFactor.fieldType) {
      case "NUMBER":
        result = (
          <InputNumber
            disabled={!configFactor.isEnabled}
            min={configFactor.valueCode === "LIMIT" ? 1 : Number("-Infinity")}
          />
        );
        break;
      case "TEXT":
        result = <Input disabled={!configFactor.isEnabled} />;
        break;
      case "LIST":
        result = this.getChooserHtml(configFactor, true);
        break;
      case "CHECKBOX":
        result = (
          <Radio.Group>
            <Radio value="NULL">{messages("common.all") /*全部*/}</Radio>
            <Radio value="Y">{messages("common.yes") /*是*/}</Radio>
            <Radio value="N">{messages("common.no") /*否*/}</Radio>
          </Radio.Group>
        );
        break;
      case "MULTY_SEL_LIST":
        result = this.getChooserHtml(configFactor, false);
        break;
      default:
        result = "";
        break;
    }
    return result;
  };

  /**
   * @description 获取Chooser selectorItem 属性
   *@param configFactor 对象
   *
   * */
  getSelectorItem = (configFactor) => {
    const searchForm = this.searchFormHandle(configFactor);
    const columns = this.columnsHandle(configFactor);
    return {
      title: `${messages("setting.key281" /*选择*/)}${
        configFactor.factorName || configFactor.fieldLabel
      }`,
      url: configFactor.url
        ? configFactor.url
        : `${config.baseUrl}/config/api/config/factor/${configFactor.id}/dataList`,
      columns: columns,
      searchForm: searchForm,
      key: "id",
      listKey: "rows",
    };
  };
  /**
   * @description 设置list类型的弹框选择
   * @param configFactor ConfigFactor
   *
   * */

  getChooserHtml = (configFactor, single) => {
    const selectorItem = this.getSelectorItem(configFactor);
    return (
      <Chooser
        selectorItem={selectorItem}
        disabled={!configFactor.isEnabled}
        valueKey="id"
        labelKey="name"
        newline={false}
        single={single}
      />
    );
  };

  /**
   *@description 获取当前的规则项
   *@param configRuleId 规则id
   * @param currentRule 当前规则id
   * @param key 判断值
   */
  getCurrentRuleItem = (configRuleId, currentRule, key) => {
    let ruleItem = configRuleId
      ? currentRule.configRuleFactorMap[key]
      : currentRule.configRuleFactors.filter(
          (rule) => rule.factorCode === key
        )[0];
    if (!ruleItem && configRuleId) {
      currentRule.configRuleFactorMap[key] = {
        factorValue: null,
        factorValueDesc: null,
      };
      ruleItem = currentRule.configRuleFactorMap[key];
    }
    return ruleItem;
  };

  /**
   * @description 校验结果节点
   *
   * */
  getConfigItemHtml(configItem) {
    const { getFieldDecorator } = this.props.form;
    const configFactor = this.configItemHandle(configItem);
    const selectorItem = this.getSelectorItem(configFactor);
    selectorItem.key = "code";
    const options = this.getOption(configFactor);
    // 设置校验规则值
    const { currentRule } = this.state;
    const value = [];
    currentRule.configRule &&
      currentRule.configRule.value &&
      value.push({
        code: currentRule.configRule.value,
        name: currentRule.configRule.valueName,
        description: currentRule.configRule.valueDesc,
      });
    options.initialValue = value;
    return (
      <div>
        {getFieldDecorator(
          configItem.itemCode,
          options
        )(
          <Chooser
            selectorItem={selectorItem}
            onChange={(value) => this.changeResultDate(value)}
            disabled={!configItem.isEnabled}
            valueKey="code"
            labelKey="name"
            newline={false}
            single
          />
        )}
      </div>
    );
  }

  /**
   * @description 修改校验结果
   *
   * */
  changeResultDate = (value) => {
    const description = value[0] ? value[0].description : "";
    this.setState({ resultDescription: description });
  };

  /**
   * @description 保存处理
   * */
  handleSave = (e) => {
    e.preventDefault();
    e.stopPropagation();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // this.setSaving(true);
        const currentRule = { ...this.state.currentRule };
        const configFactors = [...this.state.configFactors];
        const configRuleId = currentRule.configRule.id;
        configRuleId
          ? delete currentRule.configRuleFactors
          : delete currentRule.configRuleFactorMap;
        Object.keys(values).map((item) => {
          if (item === "priority") {
            currentRule.configRule.priority = parseFloat(
              values.priority
            ).toFixed(2);
          } else {
            const configFactor = configFactors.filter(
              (configFactor) => configFactor.factorCode === item
            )[0];
            const ruleItem = this.getCurrentRuleItem(
              configRuleId,
              currentRule,
              item
            ); // 获取当前数据映射
            if (!configFactor || !ruleItem) {
              return !1;
            }
            switch (configFactor.factorType) {
              case "NUMBER":
              case "TEXT":
                ruleItem.factorValue = ruleItem.factorValueDesc = values[item];
                break;
              case "CHECKBOX":
                ruleItem.factorValue = ruleItem.factorValueDesc = this.isNull(
                  values[item]
                )
                  ? null
                  : values[item];
                break;
              case "LIST":
                const value = values[item][0];
                ruleItem.factorValueDesc = value ? value.name : null;
                ruleItem.factorValue = value ? value.id : null;
                break;
              default:
                break;
            }
          }
        });
        // 添加租户信息
        const { tenantInfo } = this.props; // 租户信息
        const ruleItem = this.getCurrentRuleItem(
          configRuleId,
          currentRule,
          "TENANT"
        );
        ruleItem.factorValue = tenantInfo.id;
        // 添加校验结果
        const { configItem } = this.state;
        //当不存在values[configItem.itemCode]时，configItemValue为null
        if (configItem.resultType === "LIST") {
          const configItemValue = values[configItem.itemCode][0];
          currentRule.configRule.valueDesc = configItemValue
            ? configItemValue.description
            : null;
          currentRule.configRule.value = configItemValue
            ? configItemValue.code
            : null;
          currentRule.configRule.valueName = configItemValue
            ? configItemValue.name
            : null;
        }
        if (configItem.resultType === "DATALIST") {
          const dataConfigItem = JSON.parse(configItem.dataConfig);
          dataConfigItem.map((item, index) => {
            item.value = values[`${item.valueCode}`];
            if (item.fieldType === "MULTY_SEL_LIST") {
              const valueList = values[`${item.valueCode}`] || [];
              const ids = [];
              const names = [];
              valueList.map((item) => {
                ids.push(item.id);
                names.push(item.name);
              });
              item.value = ids.join(",");
              item.valueDesc = names.join(",");
            } else if (item.fieldType === "LIST") {
              item.value = (values[`${item.valueCode}`][0] || {}).id;
              item.valueDesc = (values[`${item.valueCode}`][0] || {}).name;
            } else {
              item.value = values[`${item.valueCode}`];
              item.valueDesc = values[`${item.valueCode}`];
            }
            dataConfigItem[index] = item;
          });
          currentRule.configRule.value = JSON.stringify(dataConfigItem);
          currentRule.configRule.valueName = JSON.stringify(dataConfigItem);
        }
        this.setState({ saving: true });
        this.saveToServer(configRuleId, currentRule)
          .then(() => {
            this.props.handleSave();
          })
          .catch(() => this.setState({ saving: false }));
      }
    });
  };

  /**
   * @description 保存信息至后台
   * @param configRuleId string 新增还是修改
   * @param currentRule ConfigurationRule data
   *
   * */
  saveToServer = (configRuleId, currentRule) => {
    return configRuleId
      ? ConfigurationCenterService.updateRule(currentRule)
      : ConfigurationCenterService.addRule(currentRule);
  };

  /**
   * @description 优先级 输入数字限制 小数后两位且为正数
   * @param value string | number
   * */
  showPriority = (value) => {
    const reg = /^[+]?\d+(?:\.\d{1,2})?/;
    const testValue = value === 0 ? `1` : `${value}`;
    let defaultVal = "";
    if (
      testValue.lastIndexOf(".") === testValue.length - 1 &&
      ~testValue.lastIndexOf(".")
    ) {
      defaultVal = ".";
      if (testValue.length === 1) {
        defaultVal = "1.";
      }
    }
    const result = reg.exec(testValue);
    return (result && `${result[0]}${defaultVal}`) || `${defaultVal}`;
  };

  render() {
    const { configFactors, saving, formItemLayout, configItem } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="edit-rule">
        <Form onSubmit={this.handleSave}>
          {/* 优先级*/}
          <FormItem
            className="priority-wrap"
            label={`${messages("setting.key270" /*优先级*/)}:`}
            {...formItemLayout}
          >
            {getFieldDecorator("priority", {
              rules: [
                {
                  required: true,
                  message: messages(
                    "setting.key282" /*请输入优先级且优先级为1或正数*/
                  ),
                },
              ],
              initialValue: this.getInitialValue("priority"),
            })(
              <InputNumber
                formatter={this.showPriority}
                parser={(value) => value}
                min={1}
              />
            )}
          </FormItem>
          <Alert
            message={messages(
              "setting.key283" /*未填值时，则表示不检查该条件*/
            )}
            type="info"
            showIcon
            style={{ marginBottom: 32 }}
          />
          {configFactors.map((item) => (
            <div key={item.factorCode}>{this.getFormItem(item)}</div>
          ))}
          {configItem.id && this.getMapItem()}
          <FormItem
            wrapperCol={{
              xs: { span: 24, offset: 0 },
              sm: { span: 16, offset: 8 },
            }}
          >
            <Button
              type="default"
              className="cancel-btn"
              onClick={this.props.close}
            >
              {" "}
              {messages("common.cancel") /*取消*/}
            </Button>
            <Button type="primary" htmlType="submit" loading={saving}>
              {" "}
              {messages("common.ok") /*确定*/}
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

EditRule.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    tenantInfo: state.login.tenant,
  };
}

const wrappedEditRule = Form.create()(EditRule);

export default connect(mapStateToProps)(wrappedEditRule);
